package com.yanyuan.snio.part;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author: yanyuan
 * @Date: 2021/3/29 11:06
 * @Description:
 * DatagramChannel 是一个能收发UDP包的通道
 *
 * 操作步骤：
 * 1.打开DatagramChannel
 * 2.接收/发送数据
 */
public class NioP11NonBlockUDP {

    public void send(List<String> msgList) throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        datagramChannel.configureBlocking(false);

        msgList.stream().forEach(msg ->{
            ByteBuffer buf = ByteBuffer.allocate(1024);
            buf.put((new Date().toString() + " \n " + msg).getBytes(StandardCharsets.UTF_8));
            buf.flip();
            try {
                datagramChannel.send(buf, new InetSocketAddress("127.0.0.1", 9898));
            } catch (IOException e) {
                e.printStackTrace();
            }
            buf.clear();
        });
        datagramChannel.close();
    }

    public void receive() throws IOException {
        DatagramChannel datagramChannel = DatagramChannel.open();
        //非阻塞
        datagramChannel.configureBlocking(false);
        datagramChannel.bind(new InetSocketAddress(9898));
        Selector selector = Selector.open();
        //监控读取模式
        datagramChannel.register(selector, SelectionKey.OP_READ);
        while (selector.select(30000L) > 0){
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                if(selectionKey.isReadable()){
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    datagramChannel.receive(buf);
                    buf.flip();
                    System.out.println(new String(buf.array(), 0, buf.limit()));
                    buf.clear();
                }
                iterator.remove();
            }
        }

    }
}
